﻿using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace DL.AI.AIBT
{
    public class BehaviourTree : BTNode
    {
        private readonly IPolicy m_Policy;
        
        public BehaviourTree(string name, IPolicy policy = null) : base(name)
        {
            m_Policy = policy ?? Policies.RunUntilFailure;
        }

        //行为树执行迭代
        public override Status Process()
        {
            var status = Children[m_CurrentChild].Process();
            if (m_Policy.ShouldReturn(status)) {
                return status;
            }
            m_CurrentChild = (m_CurrentChild + 1) % Children.Count;
            return Status.Running;
        }

        public void PrintTree() {
            StringBuilder sb = new StringBuilder();
            PrintNode(this, 0, sb);
            Debug.Log(sb.ToString());
        }

        private static void PrintNode(BTNode node, int indentLevel, StringBuilder sb) {
            sb.Append(' ', indentLevel * 2).AppendLine(node.name);
            foreach (BTNode child in node.Children) {
                PrintNode(child, indentLevel + 1, sb);
            }
        }
    }
}